package com.nnnu.wsnackshop.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.controller.base.BaseController;
import com.nnnu.wsnackshop.pojo.dto.*;
import com.nnnu.wsnackshop.pojo.entity.Members;
import com.nnnu.wsnackshop.pojo.entity.Users;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IUsersService;
import com.nnnu.wsnackshop.utils.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "用户相关接口", description = "用户相关接口")
public class UsersController extends BaseController {

    private final IUsersService userService;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户注册接口")
    public Result<Users> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        log.info("用户注册：{}", registerDTO);
        Users user = userService.register(registerDTO);
        return Result.success(user, MessageConstants.OPERATION_SUCCESSFUL);
    }

    @GetMapping("/info")
    @Operation(summary = "获取用户信息", description = "获取当前登录用户信息")
    public Result<Users> getProfile() {
        Users user = userService.getCurrentUser();
        return Result.success(user, MessageConstants.OPERATION_SUCCESSFUL);
    }

    @PutMapping("/profile")
    @Operation(summary = "更新用户信息", description = "更新当前登录用户信息")
    public Result<Map<String, Object>> updateProfile(@Valid @RequestBody UserUpdateDTO updateDTO) {
        log.info("更新用户信息：{}", updateDTO);
        Users user = userService.updateProfile(updateDTO);

        // 生成新的JWT令牌
        String newToken = JwtUtil.createTokenWithUser(user);

        // 构建返回结果，包含用户信息和新令牌
        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("token", newToken);

        return Result.success(result, MessageConstants.OPERATION_SUCCESSFUL);
    }

    @PostMapping("/password/change")
    @Operation(summary = "修改密码", description = "用户修改密码")
    public Result<Void> changePassword(@Valid @RequestBody PasswordChangeDTO changeDTO) {
        log.info("修改密码：{}", changeDTO);
        userService.changePassword(changeDTO);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }
}
